<!-- 留言榜 -->
<template>
  <div class="grid">
    <div class="col-12">
      <CommonHeaderToolBar></CommonHeaderToolBar>
    </div>
    <div id="container" class="col-12 p-5"></div>
    <div class="col-12 flex justify-content-center">
      <InputText class="w-screen"
                 v-model="inputValue"
                 placeholder="欢迎来打卡哦~输入内容，直接回车就好啦🤭"
                 @keydown.enter="sendDanmu"/>
    </div>
  </div>
</template>

<script lang="ts" setup>
/** JS */
import {ref, onMounted, onBeforeUnmount, inject, Ref} from 'vue';
import {UserMsg} from '@/interface/user/entity/UserEntityInterface';
import easyDanmaku from 'easy-danmaku-js';
import {Websocket} from '@/utils/Webscoket';
import {Message, MessageTypes} from '@/interface/websocket/entity/SocketMessage';
import Cache from '@/utils/Cache';
/** 组件 */
import CommonHeaderToolBar from '@/components/toolbar/CommonHeaderToolBar.vue';
import toast from "@/utils/Toast";

type GuestbookMessage = {
  nickname?: string
  content: string
}

const websocket: Websocket | undefined = inject('websocket'),
    messages: (Array<(event) => void>) | undefined = inject('messages'),
    cache = new Cache(),
    userMsg: UserMsg = cache.get('userMsg');
/** 弹幕 */
const inputValue = ref(''),
    openSend = ref(true),
    timer: Ref<any> = ref(null);
let userArr: Ref<string[]> = ref([]),
    guestArr: Ref<string[]> = ref([]),
    myselfArr: Ref<string[]> = ref([]),
    adminArr: Ref<string[]> = ref([]);
let Danmaku;
// 监听 socket
messages?.push((res) => {
  let msg: Message = JSON.parse(res.data);
  if (msg.type === MessageTypes.GuestBook) {
    let guestbook = JSON.parse(msg.context) as GuestbookMessage[];
    let index = 0;
    for (let book of guestbook) {
      let txt;
      // 存在 nickname
      if (book.nickname) {
        txt = `${book.nickname}: ${book.content}`;
        if (userMsg && book.nickname === userMsg.nickname) {
          // 用户自己
          myselfArr.value.push(txt);
        } else {
          // 其他用户
          userArr.value.push(txt);
        }
      } else {
        // 不存在则视为其他用户
        txt = `游客：${book.content}`;
        guestArr.value.push(txt);
      }
      index++;
    }
    Danmaku.centeredSend(adminArr.value, 'admin-danmu', 5000);
    if (myselfArr.value.length != 0) {
      Danmaku.batchSend(myselfArr.value, false, 'myself-danmu');
      if (userArr.value.length != 0) {
        Danmaku.batchSend(userArr.value);
      } else if (guestArr.value.length != 0) {
        Danmaku.batchSend(guestArr.value);
      }
    } else if (userArr.value.length != 0) {
      Danmaku.batchSend(userArr.value);
    } else if (guestArr.value.length != 0) {
      Danmaku.batchSend(guestArr.value);
    } else {
      Danmaku.batchSend([''])
    }
  }
});
onMounted(() => {
  Danmaku = new easyDanmaku({
    el: '#container',                        //弹幕挂载节点
    colourful: true,                         //彩色弹幕
    line: 7,                                //弹幕行数
    wrapperStyle: 'danmaku-wrapper',         //默认弹幕样式
    speed: 5,                                //弹幕播放速度
    runtime: 5,                            //播放一次的时常
    loop: true,                              //开启循环播放
    hover: true,                             //鼠标移入悬停
    onComplete: () => {                       //播放结束
      sendMyself();
      sendUser();
      sendGuest();
    },                                      //hover时 参数为该悬停元素
    onHover: (dom) => {
      // console.log(dom);
    }
  });
  adminArr.value.push('游客打的卡可能会被顶掉哦~~建议大家都注册登录打卡捏！O(∩_∩)O');
  // 创建弹幕完毕后连接 guestbook 列表
  websocket?.send({type: MessageTypes.GuestBook});
});

// 用户发送弹幕
const sendDanmu = () => {
      if (inputValue.value.trim() === '') {
        toast.warn('亚哒哟~', '打卡也留空是吧(￢︿̫̿￢☆)', 1500);
        return;
      }
      if (openSend.value) {
        Danmaku.send(inputValue.value, 'myself-danmu');
        myselfArr.value.push(inputValue.value);
        let context: GuestbookMessage = {
          content: inputValue.value
        }
        if (userMsg) {
          context.nickname = userMsg.nickname;
        }
        websocket?.send({type: MessageTypes.GuestBook, context: context});
        openSend.value = false;
        timer.value = setTimeout(() => {
          openSend.value = true;
          if (timer.value) {
            clearTimeout(timer.value);
            timer.value = null;
          }
        }, 5000);
        toast.success('谢谢支持', '打卡成功啦~谢谢支持！', 1500);
        inputValue.value = '';
      } else {
        toast.warn('停！每隔5秒发送', '别这么频繁发这么快，服务器会炸的(╯▔皿▔)╯', 1500);
      }
    },
    sendMyself = () => {
      for (let myself of myselfArr.value) {
        Danmaku.send(myself, 'myself-danmu');
      }
    },
    sendGuest = () => {
      for (let guest of guestArr.value) {
        Danmaku.send(guest);
      }
    },
    sendUser = () => {
      for (let user of userArr.value) {
        Danmaku.send(user);
      }
    }
onBeforeUnmount(() => {
  // 断开 guestbook 列表
  websocket?.send({type: MessageTypes.GuestBook});
  if (Danmaku) {
    Danmaku.pause();
  }
})

</script>

<style scoped>
#container {
  width: calc(100vw - 1.5rem);
  height: 400px;
}


</style>
